package com.edgclub.edg.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.utils.util.ActivityManager;
import com.edgclub.edg.utils.util.DensityUtils;
import com.hyphenate.easeui.controller.EaseUI;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.umeng.analytics.MobclickAgent;

/**
 * 底层Activity
 *
 */
public abstract class GzBaseTooolBarActivity extends AppCompatActivity implements
        OnCancelListener  {

    public LinearLayout main_back, main_search,close_web , main_back2;
    public TextView title, right_text,reful;
    public RelativeLayout right_layout,btn_more_menu;
    public  ImageView btn_collect,imgv_more , imgv_delete;
    private int p_w=450;
    private  int p_h=500;

    public RelativeLayout toolbar1 , toolbar2;

    public EditText search_src_text;
    public TextView search;

    protected InputMethodManager inputMethodManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //http://stackoverflow.com/questions/4341600/how-to-prevent-multiple-instances-of-an-activity-when-it-is-launched-with-differ/
        //理论上应该放在launcher activity,放在基类中所有集成此库的app都可以避免此问题
        if(!isTaskRoot()){
            Intent intent = getIntent();
            String action = intent.getAction();
            if(intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)){
                finish();
                return;
            }
        }
        setContentView(getContentView());
        p_w= DensityUtils.getScreenW(this); // 宽度
        p_h= DensityUtils.getScreenH(this); // 高度
        setTitleBarView();
        initView();
        initData();
        if(GuZhiApplication.isFirstMianActivity)
            ActivityManager.getInstance().addActivity(this);

        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    public abstract int getContentView();
    public abstract  void setTitleBarView();
    public abstract  void initView();
    public abstract  void initData();

    android.support.v7.app.ActionBar actionBar;
    public void setCustomActionBar() {
        android.support.v7.app.ActionBar.LayoutParams lp = new android.support.v7.app.ActionBar.LayoutParams(android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        View mActionBarView = LayoutInflater.from(this).inflate(R.layout.layout_actionbar, null);
        actionBar = getSupportActionBar();

        actionBar.setCustomView(mActionBarView, lp);
        actionBar.setDisplayOptions(android.support.v7.app.ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        title = (TextView) mActionBarView.findViewById(R.id.title);
        main_back = (LinearLayout) mActionBarView.findViewById(R.id.main_back);
        close_web= (LinearLayout) mActionBarView.findViewById(R.id.close_web);
        right_text = (TextView) mActionBarView.findViewById(R.id.right_text);
        main_search = (LinearLayout) mActionBarView.findViewById(R.id.main_search);
        right_layout = (RelativeLayout) mActionBarView.findViewById(R.id.right_layout);
        btn_collect = (ImageView) mActionBarView.findViewById(R.id.btn_collect);
        imgv_more = (ImageView) mActionBarView.findViewById(R.id.imgv_more);

        btn_more_menu = (RelativeLayout) mActionBarView.findViewById(R.id.btn_more_menu);
        reful= (TextView) mActionBarView.findViewById(R.id.reful);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.c7, getApplicationContext().getTheme()));
        } else {
            actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.c7));
        }
        main_search.setVisibility(View.GONE);
        right_layout.setVisibility(View.GONE);
        main_back.setVisibility(View.VISIBLE);
        main_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        toolbar1 = (RelativeLayout) mActionBarView.findViewById(R.id.toolbar1);
        toolbar2 = (RelativeLayout) mActionBarView.findViewById(R.id.toolbar2);
        main_back2 = (LinearLayout) mActionBarView.findViewById(R.id.main_back2);
        search_src_text = (EditText) mActionBarView.findViewById(R.id.search_src_text);
        search = (TextView) mActionBarView.findViewById(R.id.search);
        imgv_delete = (ImageView) mActionBarView.findViewById(R.id.imgv_delete);
        main_back2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //以下代码用于去除阴影
        if(Build.VERSION.SDK_INT>=21){
            getSupportActionBar().setElevation(0);
        }
    }
    public void setStatusBarHeight(boolean res){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();

                /*window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);*/
            if(res) {
                setTranslucentStatus(this, true);
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(true);
                // 使用颜色资源
                tintManager.setStatusBarTintResource(R.color.transtrant);
            }else {

                setTranslucentStatus(this, false);
                SystemBarTintManager tintManager = new SystemBarTintManager(this);
                tintManager.setStatusBarTintEnabled(true);
                tintManager.setStatusBarTintResource(R.color.c7);
            }

        }


    }
    @TargetApi(19)

    private  void setTranslucentStatus(Activity activity, boolean on) {

        Window win = activity.getWindow();

        WindowManager.LayoutParams winParams = win.getAttributes();

        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;

        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }

        win.setAttributes(winParams);

    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            ActivityManager.getInstance().removeActivity(this);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

    }



    @Override
    protected void onStop() {
        super.onStop();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

    }

    android.app.Dialog dialog;
    private Animation anim;
    /**
     * 显示dialog
     *
     * @param message
     */
    private ImageView load_image;
    private TextView load_text;
    public void setToastext(String message){
        if(dialog.isShowing()){
            load_text.setText(message);
        }
    }
    public void showDialog(String message, boolean isCanCancel) {
        if(dialog==null){
            anim = AnimationUtils.loadAnimation(this, R.anim.my_anim);
            LinearInterpolator lir = new LinearInterpolator();
            anim.setInterpolator(lir);
            dialog = new android.app.Dialog(GzBaseTooolBarActivity.this, R.style.dialog);
            Window window = dialog.getWindow();
            window.setContentView(R.layout.showdialog_layout);
            load_image = (ImageView) window.findViewById(R.id.load_image1);
            load_text = (TextView) window.findViewById(R.id.load_text);

            if (dialog != null){
                dialog.setCanceledOnTouchOutside(isCanCancel);
            }
            load_image.startAnimation(anim);
        }

        if(!dialog.isShowing()){
            load_text.setText(message);
            load_image.startAnimation(anim);
            dialog.show();
        }

    }

    private static final String TAG = "GzBaseTooolBarActivity";
    //加载动画
    private ImageView imgv_load;
    private TextView tv_load,tv_reload;
    private AnimationDrawable animationDrawable;
    private LinearLayout ll_load;
    public void showDialog1( ) {
        createDialog();
        try {
            imgv_load.setImageResource(R.drawable.loading_default);
        } catch (Exception e){
            e.printStackTrace();
        }
        if(null!=animationDrawable)
        animationDrawable.start();
        if(!dialog.isShowing()){
            dialog.show();
        }

    }
    private void createDialog(){
        if(dialog==null){
            dialog = new android.app.Dialog(GzBaseTooolBarActivity.this, R.style.dialog);
            Window window = dialog.getWindow();
            window.setContentView(R.layout.layout_load_default);
            WindowManager.LayoutParams lp = window.getAttributes();
            window.setGravity(Gravity.CENTER);
            lp.x=0;
            lp.y = 0; // 新位置Y坐标
            lp.width = p_w;
            lp.height = p_h;
            window.setAttributes(lp);
            ll_load = (LinearLayout) window.findViewById(R.id.ll_load);
            imgv_load = (ImageView) window.findViewById(R.id.imgv_load);
            tv_load = (TextView) window.findViewById(R.id.tv_load);
            tv_reload = (TextView) window.findViewById(R.id.tv_reload);
            animationDrawable = (AnimationDrawable) imgv_load.getDrawable();
            ll_load.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    Log.e(TAG, "onTouch: "+ motionEvent.getX());
                    if(null!=main_back&&null!=dialog&&dialog.isShowing()){
                        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                            if(0<motionEvent.getX()&&0<motionEvent.getY()&&motionEvent.getX()<150&&motionEvent.getY()<200){
                                finish();
                                return true;
                            }
                        }
                    }else{
                        return false;
                    }
                    return false;
                }
            });
            dialog.setCanceledOnTouchOutside(true);
            dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface dialog,
                                     int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK
                            && event.getRepeatCount() == 0) {
                        finish();
                    }
                    return false;
                }
            });
        }
    }
    public void setNoNetWork(final ReLoadClickListener reLoadClickListener){
        createDialog();
        imgv_load.setImageResource(R.drawable.no_network);
        tv_reload.setVisibility(View.VISIBLE);
        tv_load.setText("网络你去哪里了呀");
        ll_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(reLoadClickListener!=null){
                    imgv_load.setImageResource(R.drawable.loading_default);
                    tv_reload.setVisibility(View.GONE);
//					animationDrawable.start();
                    tv_load.setText("正在努力加载中...");
                    reLoadClickListener.reload();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if(tv_reload.getVisibility()==View.VISIBLE){
                    finish();
                }
            }
        });
        try {
            if(!dialog.isShowing() && !this.isFinishing()){
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void isShowingDialog(boolean isLandscape){
        if(dialog!=null && dialog.isShowing()){
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            window.setGravity(Gravity.CENTER);
            if(isLandscape){
                lp.width = p_h;
                lp.height =p_w ;
            }else{
                lp.width = p_w;
                lp.height = p_h;
            }

            window.setAttributes(lp);
        }
    }


    public interface ReLoadClickListener {
        void reload();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if(null!= dialog) {
                    if (dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialogInterface) {
                            finish();
                        }
                    });
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 取消dialog
     */
    public void dismissDialog() {
        if (null != anim)
            anim.cancel();
        if(null!=animationDrawable)
             animationDrawable.stop();
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    protected void dialogCancel(DialogInterface dialog) {
        if (null != anim)
            anim.cancel();
        if(null!=animationDrawable)
            animationDrawable.stop();
        if (null != dialog) {
            dialog.dismiss();
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        if (null != anim)
            anim.cancel();
        if(null!=animationDrawable)
            animationDrawable.stop();
        dialogCancel(dialog);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // umeng
        EaseUI.getInstance().getNotifier().reset();
        MobclickAgent.onResume(this);

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        // onPause时，暂停友盟统计
        MobclickAgent.onPause(this);
    }



    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
